package org.linphone.activities.call.receiver

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothHeadset
import android.bluetooth.BluetoothProfile
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import androidx.core.app.ActivityCompat

/**
 * @Author: Jake
 * @Date: 2023-04-23
 * @Description:
 */
const val TYPE_BT_HEADSET = 0
const val TYPE_COMMON_HEADSET = 1

class HeadsetPlugReceiver(private val headsetPlugListener: HeadsetPlugListener) : BroadcastReceiver() {

    private val TAG: String = "fvl_dbg"

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action
        Log.e(TAG, "耳机连接变化:$action")
        if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED == action) {
            Log.e(TAG, "收到蓝牙耳机广播")
            val adapter = BluetoothAdapter.getDefaultAdapter()
            if (ActivityCompat.checkSelfPermission(
                    context,
                    Manifest.permission.BLUETOOTH_CONNECT
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }
            val state = adapter.getProfileConnectionState(BluetoothProfile.HEADSET)
            if (BluetoothProfile.STATE_CONNECTED == state) {
                headsetPlugListener.onHeadsetPlug(true, TYPE_BT_HEADSET)
            } else if (BluetoothProfile.STATE_DISCONNECTED == state) {
                headsetPlugListener.onHeadsetPlug(false, TYPE_BT_HEADSET)
            }
        } else if (Intent.ACTION_HEADSET_PLUG == action) {
            Log.e(TAG, "收到有线耳机广播")
            if (intent.hasExtra("state")) {
                if (intent.getIntExtra("state", 0) == 0) {
                    headsetPlugListener.onHeadsetPlug(false, TYPE_COMMON_HEADSET)
                } else if (intent.getIntExtra("state", 0) == 1) {
                    headsetPlugListener.onHeadsetPlug(true, TYPE_COMMON_HEADSET)
                }
            }
        }
    }

    /**
     * type 表示耳机类型
     * 0 : 蓝牙耳机
     * 1 : 普通耳机
     *
     */
    interface HeadsetPlugListener {
        fun onHeadsetPlug(isPlug: Boolean, type: Int)
    }
}
